package com.leyuangame.core.service.impl;

import com.leyuangame.core.controller.bean.ResponseHandler.LeYuanResult;
import com.leyuangame.core.model.Game;
import com.leyuangame.core.model.GameCategory;
import com.leyuangame.core.service.LoginService;
import com.leyuangame.dao.repository.jpa.GameCategoryRepository;
import com.leyuangame.dao.repository.jpa.GameRepository;
import com.leyuangame.dao.repository.jpa.PlayUserRepository;
import com.leyuangame.dao.repository.jpa.user.PlayUser;
import com.leyuangame.utils.UKTools;
import org.apache.commons.lang.StringUtils;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class LoginServiceImpl implements LoginService {
    @Autowired
    private PlayUserRepository playUserRepository;
    @Autowired
    private GameCategoryRepository gameCategoryRepository;
    @Autowired
    private GameRepository gameRepository;
    @Override
    public LeYuanResult login(String phone, String passwd, String code) {
        Map<String,Object> res = new HashMap<>();
        PlayUser exits = null;
        //密码登陆
        if(!StringUtils.isEmpty(phone)&&!StringUtils.isEmpty(passwd)){
            exits = playUserRepository.findPlayUserByMobileAndPassword(phone, UKTools.md5(passwd));
        }
        //TODO 验证码登陆
        if(!StringUtils.isEmpty(phone)&&!StringUtils.isEmpty(code)) {
        }
        if(exits==null){
            return LeYuanResult.build(1,"用户名或密码不正确");
        }
//        List<GameCategory> gameCate = gameCategoryRepository.findGameCategoriesByIsopenOrderBySort(0);
        List<Game> games = gameRepository.findGamesByIsopenOrderBySort(0);
        //返回相关分类信息
        Map<String,Object> userinfo= new HashMap<>();
        userinfo.put("phone",exits.getMobile());
        userinfo.put("id",exits.getId());
        userinfo.put("token",exits.getToken());
        userinfo.put("username",exits.getUsername());
        userinfo.put("goldcoins",exits.getGoldcoins());
        userinfo.put("is_safepasswd",exits.getSafe_passwd()==null?1:0);
        res.put("userinfo",userinfo);
        return LeYuanResult.ok(res);
    }
}
